

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class DbUtil {
	
	static Logger logger = LoggerFactory.getLogger(DbUtil.class);
//	static WcsLog logger = LogUtil.getLogger(DbUtil.class);
	public static DataSource dataSource = null;
	
	private final static int RECONNECTION_TIME = 5;//数据库重连时间单位(秒)
	
	//druid连接池配置信息
	static {
		Properties propertiesDruid = new Properties();
		InputStream is = DbUtil.class.getResourceAsStream("/druid.properties");
		try {
			propertiesDruid.load(is);
		} catch (IOException e) {
			logger.error("读取druid配置文件失败！");
			e.printStackTrace();
		}
		// 返回的是DataSource，不是DruidDataSource
		try {
			dataSource = DruidDataSourceFactory.createDataSource(propertiesDruid);
		} catch (Exception e) {
			logger.error("创建druid连接池失败！");
			
			e.printStackTrace();
		}
	}
	
	public synchronized static Connection getConnection() {
		boolean isNoConnection = true;
		Connection connection = null;
		while(isNoConnection) {
			try {
				connection = dataSource.getConnection();
//				LogUtil.setStatus("数据库连接成功！");
//				GlobalOjbectUtil.getWindow().getDbStatusLabel().setText("数据库连接成功！");
				isNoConnection = false;
			} catch (SQLException e) {
				logger.error("数据库连接失败");
//				LogUtil.setStatus("数据库连接失败！");
//				GlobalOjbectUtil.getWindow().getDbStatusLabel().setText("数据库连接失败！");
				logger.info(RECONNECTION_TIME+"秒后重新连接,请检查数据库配置并确认数据库已开启！");
				try {
					Thread.sleep(RECONNECTION_TIME * 1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				
				e.printStackTrace();
			}
		}
	
		
		return connection;
	}
}
